﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Modules;
using IronPython.Compiler;
using System.IO;

namespace CivonyHelper
{
    public class PythonPlugins
    {
        private PythonEngine pyEngine = new PythonEngine();
        private MainForm MainWindow;
        
        public PythonPlugins(MainForm ContentForm)
        {
            MainWindow = ContentForm;
            RegisterPythonGlobals();
            StartPlugins();
        }

        public void RegisterPythonGlobals()
        {
            pyEngine.Globals.Add("MainWindow", MainWindow);
            pyEngine.Globals.Add("PluginManager", this);
        }

        public void RunPlugin(string ScriptName)
        {
            try
            {
               CompiledCode Code = pyEngine.CompileFile(ScriptName);
               Code.Execute();
            }
            catch (Exception E)
            {
                MainWindow.Text = E.Message.ToString();
                MessageBox.Show(E.Message.ToString());
            }
        }

        public void StartPlugins()
        {
            DirectoryInfo di = new DirectoryInfo("./Plugins/");
            FileInfo[] rgFiles = di.GetFiles("*.py");
            foreach (FileInfo fi in rgFiles)
            {
                RunPlugin("./Plugins/" + fi.Name);
            }
        }

        public void ReloadPlugins()
        {
            StartPlugins();
        }
    }
}
